import store from '@/store'

let curBtn
function openDialog() {
	store.commit('formDialog/CHANGE_FORMJSONID', curBtn.menuAssemblyHref)
	store.commit('formDialog/CHANGE_TITLE', curBtn.menuName)
	store.commit('formDialog/CHANGE_OPEN', true)
}
function checkPermission(el, binding, vnode) {
	const { value } = binding
	const { context } = vnode
	if (value && value instanceof Array && value.length === 2) {
		let code = value[0]
		let handler = value[1]
		const curRoute = store.getters && store.getters.curRoute
		let btnList = curRoute?.buttonList || []
		curBtn = btnList.find(i => i.menuHref === code)
		// console.log(curBtn)
		if (curBtn && curBtn.menuAssemblyHref) {
			// do some
			el.addEventListener('click', openDialog)
		} else {
			el.addEventListener('click', context[handler])
		}
	} else {
		throw new Error(`need roles! Like v-permission="['code','handler']"`)
	}
}
function unbindPermission(el, binding, vnode) {
	const { value } = binding
	const { context } = vnode
	if (value && value instanceof Array && value.length === 2) {
		let code = value[0]
		let handler = value[1]
		const curRoute = store.getters && store.getters.curRoute
		let btnList = curRoute?.buttonList || []
		curBtn = btnList.find(i => i.menuHref === code)
		if (curBtn && curBtn.menuAssemblyHref) {
			el.removeEventListener('click', openDialog(curBtn))
		} else {
			el.removeEventListener('click', context[handler])
		}
	} else {
		throw new Error(`need roles! Like v-permission="['code','handler']"`)
	}
}
export default {
	bind(el, binding, vnode) {
		checkPermission(el, binding, vnode)
	},
	unbind(el, binding, vnode) {
		unbindPermission(el, binding, vnode)
	},
}
